---
import type { Props } from "@astrojs/starlight/props";
import Default from "@astrojs/starlight/components/PageSidebar.astro";
import Ads from "@/components/Ads.astro";
---

<div class="toc">
  <Default {...Astro.props}>
    <slot />
  </Default>
</div>

<div class="ad">
  <Ads />
</div>

<script lang="js" is:inline>
  document.addEventListener("DOMContentLoaded", function () {
    const toc = document.querySelector(".toc");
    const ad = document.querySelector(".ad");

    function adjustLayout() {
      const windowHeight = window.innerHeight;
      const adHeight = ad.offsetHeight;

      toc.style.maxHeight = `${windowHeight - adHeight - 64}px`;
      if (toc.offsetHeight + adHeight > windowHeight) {
        ad.classList.add("fixed-ad");
      } else {
        ad.classList.remove("fixed-ad");
      }
    }

    let adHeight = ad.offsetHeight;
    let heightCheckInterval;
    function startHeightCheck() {
      clearInterval(heightCheckInterval);
      heightCheckInterval = setInterval(() => {
        const newAdHeight = ad.offsetHeight;
        if (newAdHeight !== adHeight) {
          adHeight = newAdHeight;
        } else {
          clearInterval(heightCheckInterval);
          adjustLayout();
        }
      }, 100); // 每100毫秒检查一次高度
    }

    // 监测内容变化时重新布局
    const observer = new MutationObserver(startHeightCheck);
    observer.observe(ad, { childList: true, subtree: true });
    // 检测窗口变化时重新布局
    window.addEventListener("resize", adjustLayout);
    adjustLayout();
  });
</script>

<style>
  .toc {
    overflow-y: auto; /* 允许 TOC 内部滚动 */
  }
  .fixed-ad {
    position: fixed;
    bottom: 0;
    width: 100%;
  }
</style>
